// store/modules/decorations.js
import Vue from 'vue';

const state = () => ({
    items: [],
    selectedId: null
});

const mutations = {
    ADD_DECORATION(state, payload) {
        state.items.push(payload);
        state.selectedId = payload.id;
    },
    UPDATE_DECORATION(state, { id, properties }) {
        const decoration = state.items.find(item => item.id === id);
        if (decoration) {
            // Use Vue.set for reactivity when modifying nested objects
            Vue.set(decoration, 'properties', {
                ...decoration.properties,
                ...properties
            });
        }
    },
    REMOVE_DECORATION(state, id) {
        state.items = state.items.filter(item => item.id !== id);
        if (state.selectedId === id) {
            state.selectedId = null;
        }
    },
    SET_SELECTED_DECORATION(state, id) {
        state.selectedId = id;
    },
    LOAD_SAVED_DECORATIONS(state, payload) {
        state.items = payload;
        state.selectedId = null;
    },
    CLEAR_DECORATIONS(state) {
        state.items = [];
        state.selectedId = null;
    }
};

const actions = {
    addDecoration({ commit }, decoration) {
        commit('ADD_DECORATION', decoration);
    },
    updateDecoration({ commit }, payload) {
        commit('UPDATE_DECORATION', payload);
    },
    removeDecoration({ commit }, id) {
        commit('REMOVE_DECORATION', id);
    },
    setSelectedDecoration({ commit }, id) {
        commit('SET_SELECTED_DECORATION', id);
    },
    loadSavedDecorations({ commit }, decorations) {
        commit('LOAD_SAVED_DECORATIONS', decorations);
    },
    clearDecorations({ commit }) {
        commit('CLEAR_DECORATIONS');
    }
};

const getters = {
    decorations: state => state.items,
    selectedDecoration: state => state.items.find(item => item.id === state.selectedId),
    selectedDecorationId: state => state.selectedId,
    textDecorations: state => state.items.filter(item => item.type === 'text'),
    imageDecorations: state => state.items.filter(item => item.type === 'image')
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
};